function writeResults(results) {
    var html = '';
    for (var pNum = 0; pNum < results.length; pNum++) {
        var result = results[pNum];
        var playerWords = results[pNum].words;
        playerWords.sort();

        html += '<div class="playerResult">';

        html += '<h1>'+results[pNum].name+'</h1>'

        for (var wNum = 0; wNum < playerWords.length; wNum++) {
            var word = playerWords[wNum];
            if (result.scoredWords[word]) {
                html += '<li class="scored">' + word + '</li>';
            }
            else {
                html += '<li class="unscored">' + word + '</li>';
            }

        }
        html += '<div class="score">' + results[pNum].score + '</div>';

        html += '</div>';
    }

    document.getElementById('results').innerHTML = html;

    document.getElementById('mainDiv').style.display = 'none';
    document.getElementById('results').style.display = 'block';
}

function score(results) {
    var usedWords = {};
    // populate count of used words
    for (var pNum = 0; pNum < results.length; pNum++) {
        var playerWords = results[pNum].words;
        for (var wNum = 0; wNum < playerWords.length; wNum++) {
            var word = playerWords[wNum];
            if (word in usedWords) {
                usedWords[word] += 1;
            }
            else {
                usedWords[word] = 1;
            }
        }
    }

    // actually score the words if they are only used by this person
    for (var pNum = 0; pNum < results.length; pNum++) {
        var result = results[pNum];
        result.score = 0;
        result.scoredWords = {};
        var playerWords = result.words;
        for (var wNum = 0; wNum < playerWords.length; wNum++) {
            var word = playerWords[wNum];
            if (usedWords[word] == 1) {
                result.score += scoreWord(word);
                result.scoredWords[word] = true;
            }
        }
    }
}

function scoreWord(word) {
    return (word.length - 2);
}

function testResults() {
    var results = [{
        name: 'Matt',
        words: ['one', 'two', 'three']
    },{
        name: 'Mike',
        words: ['four', 'five', 'six', 'two']
    },{
        name: 'Anja',
        words: ['three', 'two', 'seven', 'one']
    }];
    score(results);
    writeResults(results);
}
